package cn.wzl.tanks.abstractfactory;

import cn.wzl.tanks.*;

import java.awt.*;
import java.util.Random;

/**
 * @author weiZhiLin
 * @version 1.0
 * @date 2021/5/9 18:23
 */
public class Tank extends BaseTank {
    public Random random = new Random();

    public Tank(int x, int y, Dir dir, Frame frame, Group group) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.frame = (TankFrame) frame;
        this.group = group;
        // 判断开火策略
        checkFire();
    }

    // 判断开火策略
    private void checkFire() {
        if (Group.GOOD.equals(this.group)) {
            this.f = new DirFire();
            return;
        }
        this.f = new DefaultFire();
    }

    public void paint(Graphics g) {
        if (!living) return;
        randomFire();
        switch (dir) {
            case DOWN:
                g.drawImage(ResourceMrg.TDIMG, x, y, null);
                break;
            case UP:
                g.drawImage(ResourceMrg.TUIMG, x, y, null);
                break;
            case LEFT:
                g.drawImage(ResourceMrg.TLIMG, x, y, null);
                break;
            case RIGHT:
                g.drawImage(ResourceMrg.TRIMG, x, y, null);
        }
        // 边界检测
        checkOut();
        move();
    }

    private void move() {
        if (!moving) {
            return;
        }
        switch (dir) {
            case DOWN:
                y += SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
        }
        // 随机换方向
        randomDir();

    }

    // 边界检测
    private void checkOut() {
        if (this.x > TankFrame.GAME_WIDTH - Tank.WIDTH - 2) {
            this.x = TankFrame.GAME_WIDTH - Tank.WIDTH - 2;
        }
        if (this.y > TankFrame.GAME_HEIGHT - Tank.HEIGHT - 2) {
            this.y = TankFrame.GAME_HEIGHT - Tank.HEIGHT - 2;
        }
        if (this.x - 2 < 0) {
            this.x = 2;
        }
        if (this.y - 28 < 0) {
            this.y = 28;
        }
    }

    // 随机更换方向
    private void randomDir() {
        if (random.nextInt(100) > 95) {
            this.dir = Dir.values()[random.nextInt(4)];
        }
    }

    public void fire() {
        f.fire(this);
    }

    // 敌方坦克随机开火
    private void randomFire() {
        if (Group.GOOD == group) {
            return;
        }
        if (random.nextInt(10) > 8) {
            fire();
        }
    }
}
